
import config from "config";

let env = config.appEnv;
let hostName= window.location.hostname
if(env === 'uat' || hostName.startsWith('uat')){
  env= 'uat'
} else if(env === 'stage' || hostName.startsWith('stage')){
  env= 'stage'
} else if(env === 'dev'){
  env= 'uat'
} else {
  env = 'prod'
}

function createXmlHttp() {
  var xmlHttp;
  try {
    xmlHttp = new XMLHttpRequest();
  } catch (e) {
    try {
      xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
    } catch (e) {
      try {
        xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
      } catch (e) {
        console.log('浏览器太老，不能使用ajax');
      }
    }
  }
  return xmlHttp;
}

function ajax(url, isAsync, callBack) {
  var v = {};
  var xmlHttp = createXmlHttp();
  xmlHttp.open("GET", url, isAsync);
  xmlHttp.onreadystatechange = function () {
    if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
      v = xmlHttp.responseText;
      callBack && callBack(v)
    }
  };
  xmlHttp.send(null);
  return v
}

function isJSON(str) {
  if (typeof str === 'string') {
    try {
      var obj = JSON.parse(str);
      if(typeof obj == 'object' && obj){
        return obj;
      }else{
        return {};
      }
    } catch(e) {
      return {};
    }
  }
}

export default {
  getData: function (wrapperData, lang) {
    var localHash = localStorage.getItem(`language-hash-${lang}`);
    var v = {};
    try {
      v = JSON.parse(ajax(`/operationservice/public/multilanguage/release?environment=${env}&client=web`, false));
    } catch (e) {
      v.hash = localHash
    }
    let nowLangJson = localHash ? localStorage.getItem(`language-${localHash}-${lang}`) : '{}';
    if (!localHash || localHash !== v.hash) {
      let data = {};
      try {
        data = isJSON(ajax(`https://cloudhelios-static.oss-cn-shanghai.aliyuncs.com/multilanguage/web_${env}_${lang}.json`, false));
        if (!data) {
          throw new Error('no data');
        }
      } catch (e) {
        data = isJSON(ajax(`/multilanguage/web_${env}_${lang}.json`, false));
      }
      if (data) {
        localStorage.setItem(`language-hash-${lang}`, v.hash);
        localHash && localStorage.removeItem(`language-${localHash}-${lang}`);
        localStorage.setItem(`language-${v.hash}-${lang}`, JSON.stringify(data));
      } else {
        data = JSON.parse(nowLangJson);
      }
      Object.assign(wrapperData, data)
    } else {
      Object.assign(wrapperData, JSON.parse(nowLangJson))
    }
  }
}
